/*
 * @Description: 路由守卫，权限验证
 * @Author: liushuang
 * @Date: 2022-03-27 00:54:54
 * @LastEditTime: 2022-09-19 18:06:41
 */
import store from '@/store'
import NProgress from 'nprogress'
import router from '@/router'

const routesWhiteList = ['/login', '/404'] // 不经过校验的路由

const recordRoute = false // token失效回退到登录页时是否记录本次的路由
router.beforeEach(async (to, from, next) => {
  const allRealPath = store.state.routes.routes
  // 没有首页权限的情况
  if (
    to.name === '404'
    && (from.name === 'Login' || from.path === '/')
    && allRealPath.length > 0
  ) {
    next({
      path: allRealPath.filter((item) => item.meta && !item.meta.hidden && !item.meta.windowOpen)[0].path
    })
  }
  if (!NProgress.isStarted()) {
    NProgress.start()
  }
  let { hasToken } = store.state.user
  hasToken = hasToken || localStorage.getItem('hasToken')
  const userInfo = JSON.parse(localStorage.getItem('userInfo'))
  if (userInfo) {
    store.commit('user/setUserInfo', userInfo)
  } else {
    hasToken = false
  }
  if (hasToken) {
    store.commit('user/setHasToken', hasToken)

    if (to.path === '/login') {
      next({ path: '/' })
    } else {
      const hasRoles = store.getters['user/admin'] || store.getters['user/roles'].length > 0
      if (hasRoles) {
        next()
      } else {
        const getUserInfoResult = await store.dispatch('user/getUserInfo')
        if (!getUserInfoResult) {
          store.dispatch('user/resetAll')
          next('/login')
        } else {
          const accessRoutes = await store.dispatch('routes/setRoutes')
          accessRoutes.forEach((item) => {
            router.addRoute(item)
          })

          next({ ...to, replace: true })
        }
      }
    }
  } else if (routesWhiteList.indexOf(to.path) !== -1) {
    next()
  } else if (recordRoute) {
    next({ path: '/login', query: { redirect: to.path }, replace: true })
  } else next({ path: '/login', replace: true })
})

router.afterEach(() => {
  NProgress.done()
})
